<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../../include/tag.jsp" %>
<%@ page import="com.party.core.model.system.TargetType" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${member == null ? '发布' : '编辑'}文章</title>
    <%@include file="../../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <style>
        .tag-wrap-category {
            border: 1px solid #f1eeec;
            min-height: 45px;
            min-width: 300px;
            padding: 5px;
            float: left;
            margin-right: 10px;
        }

        .tag-wrap-category .tag-item-category {
            float: left;
            margin: 5px 10px 5px 5px;
            padding: 5px 10px;
            background: #fff0f3;
            position: relative;
        }

        .tag-wrap-category .tag-name-category {
            line-height: 25px;
            display: inline-block;
            vertical-align: middle;
            float: left;
            margin-right: 5px;
        }

        .tag-wrap-category .tag-item-category .category-opt {
            vertical-align: sub;
            color: #e8473f;
        }

        .tag-wrap-category .tag-item-category.active {
            color: #fff;
            background: #f4615c;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/service/article/save.do">
                    <input type="hidden" name="id" value="${article.id}"/>
                    <input type="hidden" name="members" value="" id="members"/>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">显示合作商<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="radio" name="isShowAll" lay-filter="partner" lay-verify="partner" value="1"
                                ${article.isShowAll == 1 ? 'checked' : ''}
                                       title="全部合作商">
                                <input type="radio" name="isShowAll" lay-filter="partner" lay-verify="partner" value="0"
                                ${article.isShowAll == 0 ? 'checked' : ''}
                                       title="单独显示">
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item selectedMember ${article.isShowAll == 0 ? '' : 'dn'}">
                        <div class="layui-inline">
                            <label class="layui-form-label">&emsp;&emsp;</label>
                            <div class="layui-input-block">
                                <a href="javascript:txz.selectMemberUtil.selectMember('.selectedMember .tag-wrap');"
                                   class="layui-btn layui-btn-danger">选择合作商</a>
                                <div class="tag-wrap" style="max-width: 900px; min-width: 500px">
                                    <c:forEach var="member" items="${members}">
                                        <div class="tag-item" data-id="${member.id}">
                                            <span class="tag-name">${member.realname}</span>
                                            <span name="event_form_item_ctrl" class="icon-close-new"></span>
                                        </div>
                                    </c:forEach>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">标题<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block"
                             style="width: calc(100% - 50%); float: left; margin-left: 0; margin-right: 10px;">
                            <input type="text" name="title" lay-verify="title" maxlength="50" autocomplete="off"
                                   placeholder="标题"
                                   class="layui-input" value="${article.title}">
                        </div>
                        <div class="layui-form-mid layui-word-aux">标题最多50字符</div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">封面图<span class="f-verify-red">*</span></label>
                        <div class="cover-content">
                            <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${article.pic}"/>
                            <c:if test="${article == null || empty article.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url(${ctx}/image/posterImg.png)"></span>
                            </c:if>
                            <c:if test="${article != null && not empty article.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url('${article.pic}')"></span>
                            </c:if>
                            <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加封面图</a>
                            <div class="form-word-aux">建议尺寸：800x450</div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">指南分类<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="hidden" name="categoryList" id="categoryIds" value=""
                                   lay-verify="categoryList"/>
                            <div class="tag-wrap-category">
                                <c:forEach var="category" items="${categoryList}">
                                    <div class="tag-item-category" data-id="${category.id}">
                                        <span class="tag-name-category">${category.name}</span>
                                        <i class="iconfont icon-close category-opt"></i>
                                    </div>
                                </c:forEach>
                            </div>
                            <a href="javascript:selectCategory();" class="layui-btn layui-btn-danger addCategoryBtn"
                               style="float: left; margin-right: 10px;">
                                <i class="iconfont icon-add btn-icon"></i>
                                选择分类
                            </a>
                            <div class="layui-form-mid layui-word-aux"><a
                                    href="${ctx}/service/article/guidetype/list.do" class="red">新增分类</a>
                            </div>
                            <i class="cl"></i>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">排序</label>
                            <div class="layui-input-inline">
                                <input type="text" name="sort" lay-verify="sort" autocomplete="off" class="layui-input"
                                       value="${article.sort}">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">文章内容来源<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="radio" name="type" lay-filter="type" lay-verify="type" value="local"
                                       title="本地发布"
                                ${article == null ||article.type == null|| article.type == ''|| article.type == 'local' ? 'checked="checked"' : ''}>
                                <input type="radio" name="type"
                                       lay-filter="type" lay-verify="type" value="out" title="指向外部链接"
                                ${article != null && article.type == 'out' ? 'checked="checked"' : ''}>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item"
                         id="urlDiv" ${article != null && article.type == "out" ? '' : 'style="display: none;"'}>
                        <label class="layui-form-label">链接<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="url" class="layui-input" value="${article.url}" lay-verify="url"
                                   id="url"
                                   placeholder="以http://开头"/>
                        </div>
                    </div>
                    <div class="layui-form-item"
                         id="localDiv" ${article == null || article.type == null || article.type == ''|| article.type == "local" ? '' : 'style="display: none;"'}>
                        <label class="layui-form-label">内容<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <script id="ueditor1" type="text/plain"></script>
                            <div style="display: none" id="contentView">${article.content}</div>
                            <input type="hidden" name="content" id="content" lay-verify="content"/>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <a href="${ctx}/service/article/list.do" class="layui-btn layui-btn-primary">取消</a>
                        </div>
                    </div>
                </form>
            </div>
        </div><!--底部-->
        <%@include file="../../include/footer.jsp" %>
    </section>
    <%@include file="../../notify/selectMemberInclude.jsp" %>
</div>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script>
    var ue = UE.getEditor('ueditor1', {
        initialFrameHeight: 500,//设置编辑器高度
        scaleEnabled: true
    });


    $(function () {
        layui.use(['form'], function () {
            var form = layui.form, laydate = layui.laydate;
            var formcache;
            var typeRadioValue = null;

            form.on('radio(type)', function (data) {
                typeRadioValue = data.value;
                if (typeRadioValue == "out") {
                    $("#urlDiv").show();
                    $("#localDiv").hide();
                } else if (typeRadioValue == "local") {
                    $("#urlDiv").hide();
                    $("#localDiv").show();
                }
            });
            form.on('radio(partner)', function (data) {
                if (data.value == 0) {
                    // 部分合作商
                    $(".selectedMember").removeClass("dn");
                } else {
                    // 全部合作商
                    $(".selectedMember").find('.tag-wrap').html('');
                    $(".selectedMember").addClass("dn");
                }
            });

            //自定义验证规则
            form.verify({
                partner: function (value) {
                    var checkLength = $('[name=isShowAll]:checked').length;
                    if (checkLength == 0) {
                        return "请选择是否显示合作商";
                    } else {
                        var checkValue = $('[name=isShowAll]:checked').val();
                        if (checkValue == 0) {
                            var _array = new Array();
                            $(".selectedMember .tag-wrap").find('.tag-item').each(function (index, ele) {
                                _array.push($(ele).data('id'));
                            })
                            if (_array.length == 0) {
                                return "请选择需要显示的合作商";
                            }
                        }
                    }
                },
                title: function (value) {
                    if (value == "") {
                        return '请填写文章标题';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传文章封面图";
                    }
                },
                applyUrl: function (value) {
                    if ($('[name=showApply]:checked').val() == 1) {
                        if (value == "") {
                            return "请设置按钮链接";
                        }
                    }
                },
                categoryList: function (value) {
                    var length = $(".tag-item-category").length;
                    if (length == 0) {
                        return "请选择分类";
                    }
                },
                sort: function (value) {
                    if (!util.checkNumber(value)) {
                        return "请输入正确的数字";
                    }
                },
                url: function (value) {
                    if (typeRadioValue == null) {
                        var type = $("[name=type]:checked").val();
                        if (type == "out") {
                            if (value == "") {
                                return "请填写外部链接";
                            } else if (!util.checkLink(value)) {
                                return "外部链接格式错误";
                            }
                        }
                    } else {
                        if (typeRadioValue == "out") {
                            if (value == "") {
                                return "请填写外部链接";
                            } else if (!util.checkLink(value)) {
                                return "外部链接格式错误";
                            }
                        }
                    }
                },
                content: function (value) {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (typeRadioValue == null) {
                        var type = $("[name=type]:checked").val();
                        if (type == "local") {
                            if (content == "") {
                                return "请填写文章内容";
                            }
                        }
                    } else {
                        if (typeRadioValue == "local") {
                            if (content == "") {
                                return "请填写文章内容";
                            }
                        }
                    }
                }
            });
            form.render(); //更新全部

            //监听提交
            form.on('submit', function (data) {
                submitForm(data);
                localStorage.removeItem("server_epCategory");
            });

            function getFormData() {

                //合作商类型
                var _membersArray = new Array();
                $(".tag-wrap .tag-item").each(function (index, elem) {
                    var memberId = $(elem).data("id");
                    _membersArray.push(memberId);
                });
                var memberIds = _membersArray.join(",");
                $("#members").val(memberIds);

                // 指南类型
                var _giftArray = new Array();
                var _categoryArray = new Array();
                $(".tag-wrap-category .tag-item-category").each(function (index, elem) {
                    var tagId = $(elem).data("id");
                    var tagName = $(elem).find(".tag-name-category").text();
                    _giftArray.push(tagId);
                    var map = {
                        id: tagId,
                        name: tagName
                    };
                    _categoryArray.push(map);
                });
                if (_giftArray.length > 0) {
                    $("#categoryIds").val(_giftArray.join(","));
                    $("[name=categoryCache]").val(JSON.stringify(_categoryArray));
                }


                $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
                return util.serializeForm($('#myForm').serializeArray());
            }

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    var formData = getFormData();
                    var action = $("#myForm").attr("action");
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    location.href = "${ctx}/service/article/list.do"
                                });
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    });
                })
            }


        });
        ue.addListener('ready', function () {
            this.setContent($("#contentView").html());
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });
        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.ARTICLE.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
    })

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    $(".tag-wrap-category").delegate(".category-opt", "click", function (e) {
        var target = $(e.target);
        var value = $(target).closest(".tag-item-category").data("id");
        $(target).closest(".tag-item-category").remove();

        var giftJson = localStorage.getItem("server_epCategory");
        var _giftArray = eval(giftJson);

        var index = -1; // 如果不存在返回-1，否则返回index
        $.each(_giftArray, function (ii, dd) {
            if (value == dd.id) {
                index = ii;
            }
        });
        _giftArray.splice(index, 1);
        localStorage.setItem("server_epCategory", JSON.stringify(_giftArray));
    })


    function selectCategory() {
        function cb($jquery) {
            var categoryIds = $($jquery.find("#categoryIds")).val();
            var categoryNames = $($jquery.find("#categoryNames")).val();
            var _idsArray = categoryIds.split(",");
            var _namesArray = categoryNames.split(",");
            var _contentArray = new Array();
            for (var i = 0; i < _idsArray.length; i++) {
                _contentArray.push('<div class="tag-item-category" data-id="' + _idsArray[i] + '">');
                _contentArray.push('<span class="tag-name-category">' + _namesArray[i] + '</span>');
                _contentArray.push('<i class="iconfont icon-close category-opt"></i>');
                _contentArray.push('</div>');
            }
            var $content = $(".tag-wrap-category");
            $content.html(_contentArray.join(""));

        }

        var _giftArray = new Array();
        $(".tag-wrap-category .tag-item-category").each(function (index, elem) {
            var giftId = $(elem).data("id");
            _giftArray.push(giftId);
        });
        var categoryIds = _giftArray.join(",");

        openDialog('选择分类', '${ctx}/service/article/guidetype/selectServiceGuideTypeList.do?categoryIds=' + categoryIds, '450px', '600px', cb);
    }

    function openDialog(title, url, width, height, cb, target) {
        layer.open({
            type: 2,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url,
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                var inputForm = body.find('#inputForm');
                var top_iframe;
                if (target) {
                    top_iframe = target;//如果指定了iframe，则在改frame中跳转
                } else {
                    top_iframe = '_parent';//获取当前active的tab的iframe
                }
                inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                if (iframeWin.contentWindow.doSubmit()) {
                    cb(iframeWin.contentWindow.$);

                    setTimeout(function () {
                        top.layer.close(index);
                    }, 100);//延时0.1秒，对应360 7.1版本bug
                }

            },
            cancel: function (index) {
            }
        });
    }


</script>
</body>
<script type="text/javascript">
    txz.initHeader({
        nav: [{
            name: '服务指南',
            href: '${ctx}/service/article/list.do'
        }, {
            name: '${member == null ? '发布' : '编辑'}文章',
            curr: true
        }],
        btns: [{
            name: '返回',
            href: '${ctx}/service/article/list.do',
            icon: 'back'
        }]
    });
</script>
</html>